import axios from 'axios';
import fs from 'fs';
import path from 'path';
import FormData from 'form-data';

// GeoServer 的配置
const geoserverUrl = 'http://localhost:8080/geoserver/rest';
const username = 'admin';
const password = 'geoserver';

// SHP 文件所在的目录
const shpDirectory = 'E:/marsDemo/marsDemo/public/1';

// 读取目录中的所有 SHP 文件
const shpFiles = fs.readdirSync(shpDirectory).filter(file => path.extname(file).toLowerCase() === '.shp');

// 发布 SHP 文件到 GeoServer
async function publishShpFiles() {
  for (const shpFile of shpFiles) {
    const workspace = 'wang'; // 替换为你的工作区名称
    const storeName = path.basename(shpFile, '.shp');
    const shpFilePath = path.join(shpDirectory, shpFile);

    console.log(`正在处理文件: ${shpFilePath}`);

    // 创建数据存储
    const createStorePayload = {
      dataStore: {
        name: storeName,
        type: 'Shapefile',
        connectionParameters: {
          url: `file:data/${storeName}`,
          namespace: workspace
        }
      }
    };

    try {
      // 创建数据存储
      await axios.post(`${geoserverUrl}/workspaces/${workspace}/datastores`, createStorePayload, {
        auth: {
          username,
          password
        },
        headers: {
          'Content-Type': 'application/json'
        }
      });

      console.log(`数据存储 ${storeName} 创建成功`);

      // 上传 SHP 文件
      const formData = new FormData();
      formData.append('file', fs.createReadStream(shpFilePath));

      console.log('正在上传 SHP 文件');
      
      //f"{geoserver_url}/workspaces/{workspace_name}/datastores/{title}/{data_type}/{title}.json"
      //http://localhost:8080/geoserver/rest/workspaces/wang/datastores/${storeName}/file.shp
      try {
        await axios.put(`${geoserverUrl}/workspaces/${workspace}/datastores/${storeName}/file.shp`, formData, {
          auth: {
            username,
            password
          },
          headers: {
            ...formData.getHeaders()
          }
        });

        console.log(`SHP 文件 ${shpFile} 上传成功`);
      } catch (uploadError) {
        console.error(`上传 SHP 文件 ${shpFile} 失败:`, uploadError.response ? uploadError.response.data : uploadError.message);
      }

      // 发布图层并配置属性
      const publishLayerPayload = {
        featureType: {
          name: storeName,
          nativeName: storeName,
          title: storeName,
          abstract: 'This is a description of the layer',
          enabled: true,
          srs: 'EPSG:4326', // 设置坐标参考系统
          nativeBoundingBox: {
            minx: -180,
            maxx: 180,
            miny: -90,
            maxy: 90
          },
          latLonBoundingBox: {
            minx: -180,
            maxx: 180,
            miny: -90,
            maxy: 90
          }
        }
      };

      await axios.post(`${geoserverUrl}/workspaces/${workspace}/datastores/${storeName}/featuretypes`, publishLayerPayload, {
        auth: {
          username,
          password
        },
        headers: {
          'Content-Type': 'application/json'
        }
      });

      console.log(`图层 ${storeName} 发布成功`);
    } catch (error) {
      console.error(`发布 SHP 文件 ${shpFile} 失败:`, error.response ? error.response.data : error.message);
    }
  }
}

publishShpFiles();



//   node --experimental-modules publishShp.mjs